import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:exams_app/home_module/account_set_module/account_logic.dart';
import 'package:exams_app/home_module/live_module/live_logic.dart';
import 'package:exams_app/home_module/live_module/websocket_manager.dart';
import 'package:exams_app/net/Address.dart';
import 'package:exams_app/net/persisten_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';

import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/status.dart' as status;
import 'dart:convert' as convert;




class ChatPage extends StatefulWidget {




   WebSocketChannel channel;

   List<MyMessage> list;
   //
   // ChatPage({Key key, @required this.channel})
   //     : super(key: key);

   ChatPage(this.channel,this.list);

  @override
  _ChatPageState createState() => _ChatPageState();

}

// class MessageEntity {
//   bool own;
//   String content;
//   String timeStr;
//   String name;
//   MessageEntity(this.own, this.content, this.name,[this.timeStr]);
// }

class MyMessage {
  // bool own;
  String content;
  String code;
  String name;
  var uid;
  MyMessage(this.content, this.name,this.uid);

}



class _ChatPageState extends State<ChatPage> with AutomaticKeepAliveClientMixin{

  final AccountLogic accountLogicClogic = Get.put(AccountLogic());


  bool get wantKeepAlive =>true;

  var uid ;

  var name;

   Map<String, dynamic> datajson;

  Map<String, dynamic> allJSon;


  // 信息列表
  // List<MessageEntity> _msgList = List();


  List<MyMessage> _mymsgList = List();



  // 输入框
  TextEditingController _textEditingController;

  // 滚动控制器

  ScrollController _scrollController;

  // 发送消息

  void _sendMsg(String msg){

    _sendMessage();

    _scrollController.animateTo(0.0,
        duration: Duration(milliseconds: 300), curve: Curves.linear);

    setState(() {

    });
  }

  @override
  void dispose() {
   // widget.channel.sink.close();
    super.dispose();
  }


  /// 连接 socket

  void connectSocket()async{


    name = await PersistentStorage().getStorage('name');
    uid = await PersistentStorage().getStorage('uid');

    Map<String, dynamic> b =  convert.jsonDecode('''
        {"uid":${await PersistentStorage().getStorage('uid')},"name":"app-${await PersistentStorage().getStorage('name')}","msgtype":"1"}
        ''');

    widget.channel.sink.add(
      convert.jsonEncode(b),
    );


    setState(() {

    });
  }

  @override
  void initState() {




    // _mymsgList.insert(0, MyMessage('','',''));

    _textEditingController = TextEditingController();

    _textEditingController.addListener(() {

      setState(() {

      });

    });

    _scrollController = ScrollController();


    connectSocket();


    // _easyController = EasyRefreshController();

    // TODO: implement initState
    super.initState();

    print('执行1次');
  }


  void _sendMessage()async {


    // Map<String, dynamic> b = convert.jsonEncode(MessageEntity(0,));

    Map<String, dynamic> b =  convert.jsonDecode('''
        {"uid":${uid},"name":"${name}","msgtype":2,"content":"${_textEditingController.text}"}
        ''');
    // _mymsgList.insert(0,MyMessage(_textEditingController.text, name, uid));

    if (_textEditingController.text.isNotEmpty) {
      widget.channel.sink.add(
        convert.jsonEncode(b),
      );
    }
  }


  @override
  Widget build(BuildContext context) {

    _mymsgList = widget.list;

    return Column(
      children: [
        Expanded(
            child:Container(
                child: LayoutBuilder(
                  builder: (context,constraints){
                    // 判断列表内容是否大于展示区域
                    bool overflow = false;
                    double heightTmp = 0.0;
                    for (MyMessage entity in _mymsgList) {
                      heightTmp +=
                          _calculateMsgHeight(context, constraints, entity);
                      if (heightTmp > constraints.maxHeight) {
                        overflow = true;
                      }
                    }
                    return  EasyRefresh.custom(
                      reverse: true,
                      // shrinkWrap: true,
                      scrollController: _scrollController,
                      footer: CustomFooter(
                          enableInfiniteLoad: false,
                          extent: 40.0,
                          triggerDistance: 50.0,
                          footerBuilder: (context,
                              loadState,
                              pulledExtent,
                              loadTriggerPullDistance,
                              loadIndicatorExtent,
                              axisDirection,
                              float,
                              completeDuration,
                              enableInfiniteLoad,
                              success,
                              noMore) {
                            return Stack(
                              children: <Widget>[
                                Positioned(
                                  bottom: 0.0,
                                  left: 0.0,
                                  right: 0.0,
                                  child: Container(
                                      width: 30.0,
                                      height: 30.0,
                                      child: Center(
                                        child: SizedBox(
                                          width: 24,
                                          height: 24,
                                          child: CircularProgressIndicator(
                                            strokeWidth: 3,
                                          ),
                                        ),
                                      )
                                  ),
                                ),
                              ],
                            );
                          }),
                      slivers: [
                        if (overflow)
                          SliverList(
                            delegate: SliverChildBuilderDelegate(
                                  (context, index) {
                                return _buildMsg(_mymsgList[index]);
                              },
                              childCount: _mymsgList.length,
                            ),
                          ),
                        if (!overflow)
                          SliverToBoxAdapter(
                            child: Container(
                              height: constraints.maxHeight,
                              width: double.infinity,
                              child: Column(
                                children: <Widget>[
                                  for (MyMessage entity in _mymsgList.reversed)
                                    _buildMsg(entity),
                                ],
                              ),
                            ),
                          ),
                      ],
                      // itemBuilder: _buildListItem,
                      // itemCount: _msgList.length,
                    );

                  },
                )
            )
        ),

        SafeArea(
          child: Container(
            color: Colors.grey[100],
            padding: EdgeInsets.only(
              left: 15.0,
              right: 15.0,
              top: 10.0,
              bottom: 10,
            ),
            child:  Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Container(
                    padding: EdgeInsets.only(
                      left: 5.0,
                      right: 5.0,
                      top: 10.0,
                      bottom: 15.0,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(
                        4.0,
                      )),
                    ),
                    child: TextField(
                      controller: _textEditingController,
                      decoration: null,
                      onSubmitted: (value) {
                        if (_textEditingController.text.isNotEmpty) {
                          _sendMsg(_textEditingController.text);
                          _textEditingController.text = '';
                        }
                      },
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    if (_textEditingController.text.isNotEmpty) {
                      _sendMsg(_textEditingController.text);

                      _textEditingController.text = '';
                    }
                  },
                  child: Container(
                    height: 30.0,
                    width: 60.0,
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(
                      left: 15.0,
                    ),
                    decoration: BoxDecoration(
                      color: _textEditingController.text.isEmpty
                          ? Colors.grey
                          : Theme.of(context).primaryColor,
                      borderRadius: BorderRadius.all(Radius.circular(
                        4.0,
                      )),
                    ),
                    child: Text(
                      '发送',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.0,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }


  Widget _buildMsg(MyMessage entity) {

    // if(json['act']=='heart'){
    //
    //   return null;
    // }

    print(entity.content);
    if(entity.content==''){
      return Container(
        width: Get.width,
        // color: Colors.red,
        padding: EdgeInsets.all(15),
        // height: 110,
        // color: Colors.red,
        child: Text('系统提示:直播内容及互动评论须严格遵守直播规范严禁传播违法违规、低俗血暴、吸烟酗酒、造谣诈骗等不良有害信息。请勿轻信平台上各类广告信息，谨防上当受骗',style: TextStyle(fontSize: 14,color: Theme.of(context).primaryColor),),
      );
    }

    if (entity.uid==uid) {
      return Container(
        margin: EdgeInsets.all(
          10.0,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Card(
              margin: EdgeInsets.only(
                right: 10.0,
              ),
              clipBehavior: Clip.hardEdge,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(20.0)),
              ),
              elevation: 0.0,
              // child: Container(
              //   height: 40.0,
              //   width: 40.0,
              //   child: Image.network(accountLogicClogic.userJson['data'][0]
              //   ['image_128'],fit: BoxFit.cover,),
              // ),
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  '我',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 13.0,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: 5.0,
                  ),
                  padding: EdgeInsets.all(10.0),
                  decoration: BoxDecoration(
                    color: Theme.of(context).primaryColor,
                    borderRadius: BorderRadius.all(Radius.circular(
                      4.0,
                    )),
                  ),
                  constraints: BoxConstraints(
                    maxWidth: 200.0,
                  ),
                  child: Text(
                    (entity.content) ?? '',
                    // overflow: TextOverflow.clip,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 12.0,
                    ),
                  ),
                )
              ],
            ),
          ],
        ),
      );
    }
    /// 接收方
    else {
      return Container(
        margin: EdgeInsets.all(
          10.0,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            // Card(
            //   margin: EdgeInsets.only(
            //     right: 10.0,
            //   ),
            //   clipBehavior: Clip.hardEdge,
            //   shape: RoundedRectangleBorder(
            //     borderRadius: BorderRadius.all(Radius.circular(20.0)),
            //   ),
            //   elevation: 0.0,
            //   child: Container(
            //     height: 40.0,
            //     width: 40.0,
            //     // child: Image.network(accountLogicClogic.userJson['data'][0]
            //     // ['image_128'],fit: BoxFit.cover,),
            //   ),
            // ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  '${entity.name}',
                  style: TextStyle(
                    color: Colors.grey,
                    fontSize: 13.0,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: 5.0,
                  ),
                  padding: EdgeInsets.all(10.0),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(
                      4.0,
                    )),
                  ),
                  constraints: BoxConstraints(
                    maxWidth: 200.0,
                  ),
                  child: Text(
                    (entity.content) ?? '',
                    // overflow: TextOverflow.clip,
                    style: TextStyle(
                      fontSize: 12.0,
                    ),
                  ),
                )
              ],
            ),
          ],
        ),
      );
    }


  }
  // 计算内容的高度
  double _calculateMsgHeight(
      BuildContext context, BoxConstraints constraints, MyMessage entity) {
    return 70.0 +
        _calculateTextHeight(
          context,
          constraints,
          text: '我',
          textStyle: TextStyle(
            fontSize: 13.0,
          ),
        ) +
        _calculateTextHeight(
          context,
          constraints.copyWith(
            maxWidth: 200.0,
          ),
          text: entity.content ?? '',
          textStyle: TextStyle(
            fontSize: 16.0,
          ),
        );
  }

  /// 计算Text的高度
  double _calculateTextHeight(
      BuildContext context,
      BoxConstraints constraints, {
        String text = '',
        @required TextStyle textStyle,
        List<InlineSpan> children = const [],
      }) {
    final span = TextSpan(text: text, style: textStyle, children: children);

    final richTextWidget = Text.rich(span).build(context) as RichText;
    final renderObject = richTextWidget.createRenderObject(context);
    renderObject.layout(constraints);
    return renderObject.computeMinIntrinsicHeight(constraints.maxWidth);
  }

}
